package com.huishao.api.service.impl;

import com.baomidou.mybatisplus.extension.conditions.query.QueryChainWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.huishao.api.common.R;
import com.huishao.api.common.token;
import com.huishao.api.mapper.UserMapper;
import com.huishao.api.entity.User;
import com.huishao.api.service.UserService;
import org.springframework.stereotype.Service;
import com.huishao.api.common.PageResult;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.huishao.api.utils.MybatisPlusUtil;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * (User)表服务实现类
 *
 * @author huishao
 * @since 2022-12-29 15:29:28
 */
@Service("userService")
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Override
    public PageResult getPage(Integer currentPage, Integer size, User user) {
        Page<User> page = new Page<>(currentPage, size);

        QueryWrapper<User> queryWrapper = MybatisPlusUtil.queryWrapperBuilder(user);

        this.page(page, queryWrapper);

        return new PageResult((int) page.getTotal(), page.getRecords());
    }

    @Override
    public R<Object> login(String loginName, String password) {
        if(this.baseMapper.selectOne(
                new QueryWrapper<User>()
                        .eq("login_name",loginName)
                        .eq("password",password)
        )!=null){
            // 修改上次登录时间 ！加入redis缓存 -> 返回 用户名密码 + token
            User u = new User();
            u.setLastLoginTime(new Date());
            this.baseMapper.update(u,new QueryWrapper<User>()
                    .eq("login_name",loginName)
                    .eq("password",password));
            Map<String,Object> map = new HashMap<>();
            map.put("token", token.createToken(loginName));
            map.put("User",this.baseMapper.selectOne(
                    new QueryWrapper<User>()
                            .eq("login_name",loginName)
                            .eq("password",password)
            ));
            return R.success("登录成功",map);
        }
        else {
            return R.error("登录失败");
        }

    }

    @Override
    public R<Object> loginOut(String tokenBody) {
        token.delToken(tokenBody);
        return R.ok("注销成功");
    }
}

